package com.easylive.web.controller;

import com.easylive.entity.config.AppConfig;
import com.easylive.entity.constants.Constants;
import com.easylive.entity.enums.DateTimePatternEnum;
import com.easylive.entity.enums.ResponseCodeEnum;
import com.easylive.entity.vo.ResponseVO;
import com.easylive.exception.BusinessException;
import com.easylive.utils.DateUtil;
import com.easylive.utils.FFmpegUtils;
import com.easylive.utils.StringTools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.Date;

/**
 * @Author 71740
 * @Description TODO
 * @Date 2025/4/20 21:44
 * @Version 1.0
 */
@RestController
@RequestMapping("/file")
@Slf4j
@Validated
public class FileController extends ABaseController {

    @Resource
    private AppConfig appConfig;

    @Resource
    private FFmpegUtils fFmpegUtils;

//    @RequestMapping("/uploadImage")
//    public ResponseVO uploadImage(@NotNull MultipartFile file, @NotNull Boolean createThumbnail) throws IOException {
//        String month = DateUtil.format(new Date(), DateTimePatternEnum.YYYY_MM.getPattern());
//        String folder = appConfig.getProjectFolder() + Constants.FILE_FOLDER + Constants.COVER + month;
//        File folderFile = new File(folder);
//        if (!folderFile.exists()) {
//            folderFile.mkdirs();
//        }
//        String fileSuffix = StringTools.getFileSuffix(file.getOriginalFilename());
//        String fileRealName = StringTools.getRandomString(Constants.LENGTH_30) + fileSuffix;
//        String filePath = folder + "/" + fileRealName;
//        file.transferTo(new File(filePath));
//        if (createThumbnail) {
//            fFmpegUtils.createImageThumbnail(filePath);
//        }
//        return getSuccessResponseVO(Constants.COVER + month + "/" + fileRealName);
//    }


    /**
     * @param response
     * @param sourceName 穿的参数会到cover层级 （cover/202504/**.jpg）
     * @throws IOException
     */
    @RequestMapping("/getResource")
    public void getResource(HttpServletResponse response, @NotNull String sourceName) throws IOException {
        if (!StringTools.pathIsOk(sourceName)) {
            throw new BusinessException(ResponseCodeEnum.CODE_600);
        }
        String fileSuffix = StringTools.getFileSuffix(sourceName);
        response.setContentType("image/" + fileSuffix.replace(".", ""));
        response.setHeader("Cache-Control", "max-age=2592000");
        readFile(response, sourceName);
    }

    protected void readFile(HttpServletResponse response, String filePath) {
        File baseDir = new File(appConfig.getProjectFolder(), Constants.FILE_FOLDER);
        File file = new File(baseDir, filePath);

        // 路径验证，防止路径遍历攻击
        try {
            String canonicalPath = file.getCanonicalPath();
            String baseCanonical = baseDir.getCanonicalPath();
            if (!canonicalPath.startsWith(baseCanonical)) {
                log.warn("尝试访问非法路径: {}", file.getAbsolutePath());
                return;
            }
        } catch (IOException e) {
            log.error("路径验证失败", e);
            return;
        }

        // 检查文件是否存在且是普通文件
        if (!file.exists() || !file.isFile()) {
            return;
        }

        try (OutputStream out = response.getOutputStream()) {
            Files.copy(file.toPath(), out);
        } catch (IOException e) {
            log.error("读取文件 {} 异常", file.getAbsolutePath(), e);
        }
    }

}
